package org.smartagents.body;

import org.smartagents.enviro.EnvironmentConstants;

import java.util.Map;
import java.util.HashMap;

public class BrainBuilder {

    public static Neurone brainFromString(String code) {

        Neurone cortex = null;

        String[] neurons = code.split(EnvironmentConstants.NEURONE_SEPARATOR);
        String[] details;
        Map<String, Neurone> knownNeurons = new HashMap<String, Neurone>(neurons.length);
        Neurone neurone;
        int count=0;
        for (String neu: neurons) {
            details = neu.split(EnvironmentConstants.NEURONE_DETAIL_SEPARATOR);
            neurone = buildNeurone(details[1]);
            if (count++==0) {
                cortex = neurone;
            }
            knownNeurons.put(details[0], neurone);
        }

        for (String neu: neurons) {
            details = neu.split(EnvironmentConstants.NEURONE_DETAIL_SEPARATOR);
            if (details.length>2) {
                neurone = knownNeurons.get(details[0]);
                for (int i=2; i<details.length; i++) {
                    neurone.addLink(knownNeurons.get(details[i]));
                }
            }
        }

        return cortex;
    }

    public static Neurone buildNeurone(String cond) {
        Neurone neurone = new Neurone();
        if (!"null".equals(cond)) {
            String[] condConv = cond.split(EnvironmentConstants.NEURONE_CONVERT_SEPARATOR);
            neurone.setLinkCondition(condConv[0]);
            if (condConv.length>1) {
                neurone.setAddBeforeSlot(condConv[1]);
            }
        }
        return neurone;
    }

}
